package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author brianxia
 * @version 1.0
 * @date 2023-02-12 9:43
 */
@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
@Slf4j
public class OrderCheckHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Override
    public void process(String jsonMsg) throws IOException {
        if(StringUtils.isBlank(jsonMsg)){
            log.error(TopicConfig.ORDER_CHECK_TOPIC + "参数为空");
            return;
        }

        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        String orderNo = orderCheck.getOrderNo();
        if(StringUtils.isBlank(orderNo)){
            log.error("订单确认消息订单号为空!" + jsonMsg);
            return;
        }

        //update order set status = 4 where orderNo = xxx and status = 0

        orderService.update(Wrappers.<OrderEntity>lambdaUpdate()
                .eq(OrderEntity::getOrderNo,orderNo)
                .eq(OrderEntity::getStatus, VMSystem.ORDER_STATUS_CREATE)
                .set(OrderEntity::getStatus, VMSystem.ORDER_STATUS_INVALID)
        );

        //将二维码失效
        WxPayParam wxPayParam = new WxPayParam();
        wxPayParam.setOutTradeNo(orderNo);
        try {
            this.wxPayTemplate.closeOrder(wxPayParam);
        } catch (Exception e) {
            log.error("取消支付单失败!" + jsonMsg);
        }
    }
}
